package com.jy.admin.rest;

import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Page;
import com.fqgj.exception.common.ApplicationException;
import com.jy.admin.annotations.AdminSignIgnore;
import com.jy.admin.auth.anno.VisitorAccessible;
import com.jy.admin.auth.vo.RequestLocalInfo;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.bo.common.conf.api.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class UploadController {


    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private OSSService ossService;

    /**
     * 上传图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public ApiResponse<String> uploadPicture(HttpServletRequest request) {
        String url = uploadExcel(request, true);
        return new ApiResponse<>(url).setMsg("upload success");
    }

    @RequestMapping(value = "/upload/img", method = RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public ApiResponse<String> uploadPictureImg(HttpServletRequest request) {
        String url = uploadExcel(request, false);
        return new ApiResponse<>(url).setMsg("upload success");
    }

    public String uploadExcel(HttpServletRequest request, boolean isCsvOnly) {
        String merchantCode = RequestLocalInfo.getCurrentUser().getMerchantCode();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        String contentType = multipartFile.getContentType();
        if (isCsvOnly) {
            if (!contentType.equalsIgnoreCase("text/csv")) {
                throw new ApplicationException("csv only!!");
            }
        }
        String originalFilename = multipartFile.getOriginalFilename();
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new ApplicationException("empty  upload");
        }

//        if (multipartFile.getSize() > 10000000) {
//            throw new ApplicationException("size to large");
//        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = (apolloConfigUtil.isServerTest() ? "excel/test/" + merchantCode + "/" + uuid : "excel/" + merchantCode + "/" + uuid) + originalFilename;
        ByteArrayOutputStream outputStream = null;
        InputStream in1 = null;
//        InputStream in2 = null;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            in1 = new ByteArrayInputStream(outputStream.toByteArray());
            ossService.uploadFile(apolloConfigUtil.getBucketName(), in1, multipartFile.getSize(), fileName);
//            LOGGER.info("上传成功:{},url:{}", fileName, apolloConfigUtil.getOssBaseUrl() + fileName);
        } catch (Exception e) {
//            LOGGER.error("上传失败，userCode:" + merchantCode + ",exception:" + e);
            throw new ApplicationException("picture upload failed");
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (in1 != null) {
                    in1.close();
                }
//                if (in2 != null) {
//                    in2.close();
//                }
            } catch (IOException var15) {
            }
        }
        return apolloConfigUtil.getOssBaseUrl() + "/" + fileName;
    }

}
